package com.ikaros.concurrency.example.singleton;

import com.ikaros.concurrency.annotations.ThreadSafe;

/**
 * 懒汉模式 ->双重同步锁单例模式->线程安全：单例对象加了volatile可以限制指令重排
 * 单例模式在第一次使用时进行创建
 */
@ThreadSafe
public class SingletonLanHanSafeDoubleLock {
    //私有构造函数
    private SingletonLanHanSafeDoubleLock() {
    }

    //instance = new SingletonLanHanNotSafeDoubleLock();会执行哪些操作
    //1.memory=allocate();分配对象内存空间
    //2.ctorInstance;初始化对象
    //3.instance=memory;设置instance指向刚分配的内存

    //jvm和cpu优化,发生了指令重排:ps:volatile可以限制指令重排
    //1.memory=allocate();分配对象内存空间
    //2.instance=memory;设置instance指向
    //3.ctorInstance;初始化对象
    //单例对象volatile+双重检查机制->禁止指令重排
    private volatile static SingletonLanHanSafeDoubleLock instance = null;

    //静态的工厂方法
    public static SingletonLanHanSafeDoubleLock getInstance() {
        if (instance == null) {//双重检查机制
            synchronized (SingletonLanHanSafeDoubleLock.class) {//同步锁
                if (instance == null) {
                    instance = new SingletonLanHanSafeDoubleLock();
                }
            }
        }
        return instance;
    }
}
